package com.tecode.myBooks.shoppingCart.servlet;

import com.tecode.myBooks.shoppingCart.service.ShoppingService;
import com.tecode.myBooks.user.bean.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;

/**
 * Created with Intellij IDEA.
 *
 * @Author: Gabriel
 * @Date: 2018-12-10
 * @Description:
 */
@WebServlet("/shoppingCart")
public class ShoppingServelt extends HttpServlet{

private ShoppingService shoppingService = new ShoppingService();
	protected void addCart(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String productId = req.getParameter("productId");
		int nums = 0;
		try{
			nums = Integer.valueOf(req.getParameter("nums"));

		}catch (Exception e){}
		User loginUser = (User)(req.getSession().getAttribute("loginUser"));
		int userId = loginUser.getId();

		PrintWriter out = resp.getWriter();

		//调用添加购物车的业务方法
		out.print(shoppingService.addCart(productId,nums,userId));

	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
			//1.修改请求的字符集编码
					req.setCharacterEncoding("UTF-8");
					//2.修改响应的字符集编码和类型
					resp.setCharacterEncoding("UTF-8");
					resp.setContentType("text/html");

					//3.获得处理当前请求的方法的名称   methodName    getBookList
					String methodName = req.getParameter("methodName");
					//System.out.println("methodName:" + methodName);
					try {
						//通过运行时类 来获得运行时类中的方法。
						Method method = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
						//设置运行访问到非public 的方法
						method.setAccessible(true);
						//执行方法
						method.invoke(this,req,resp);
					} catch (Exception e) {
						e.printStackTrace();
					}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
			doGet(req,resp);
	}
}